Java HashSet
The HashSet
is used to create a collection of unique values. In order to use it, we need to import the package java.util
.
Using HashSet
to store the collection of values is the best approach for searching the values since it uses the mechanism of hashing
. HashSet
cannot contain any duplicate values.
Create HashSet
import java.util.HashSet;
HashSet<String> userName= new HashSet<String>();
Add values to HashSet
The HashSet
class provides a method add()
to add values to the HashSet
.
Example to add values to HashSet
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> users = new HashSet<String>();
users.add("Andrew");
users.add("Rayan");
users.add("John");
users.add("Stephen");
users.add("Mark");
System.out.println(users);
}
}
Output
[Andrew, Rayan, John, Mark, Stephen]
Check Exists
HashSet
class has a method contains()
to check whether a particular value is present or not. It will return true
if it exists, and false
is not available in the HashSet
.
Example to check whether the value is present
users.add("Michael");
Removing values from HashSet
HashSet
class provides the remove()
method to remove a particular value from the HashSet
.
Example to remove a value from HashSet
users.remove("Stephen");
We can use the clear()
method to clear all the values in the HashSet
.
users.clear();
Looping through HashSet
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> users = new HashSet<String>();
users.add("Andrew");
users.add("Rayan");
users.add("John");
users.add("Stephen");
users.add("Mark");
System.out.println("Total users: "+ users.size());
for(String user: users){
System.out.println(user);
}
}
}
Output
Total users:5
Andrew
Rayan
John
Mark
Stephen
In the above program, we have created a HashSet
to store the list of users and used the following syntax to loop through the values of the HashSet
.
for(String user: users){
System.out.println(user);
}
To find out the number of items in the HashSet
we use size()
method.
Example for HashSet
import java.util.*;
class Employee {
int employeeId;
String name;
String designation;
public Employee(int employeeId, String name, String designation) {
this.employeeId = employeeId;
this.name = name;
this.designation = designation;
}
}
public class Main {
public static void main(String[] args) {
HashSet<Employee> employees=new HashSet<Employee>();
//Creating employees
Employee emp1=new Employee(101,"Andrew","CTO");
Employee emp2=new Employee(102,"Beslin","Business Analyst");
Employee emp3=new Employee(103,"Joanna","Architect");
//Adding employees to HashSet
employees.add(emp1);
employees.add(emp2);
employees.add(emp3);
//Traversing HashSet
for(Employee employee:employees){
System.out.println(employee.employeeId+" "+employee.name+" "+employee.designation);
}
}
}
Output
101 Andrew CTO
103 Joanna Architect
102 Beslin Business Analyst